import { useState } from 'react'
import { Upload } from 'antd'
import { PlusOutlined } from '@ant-design/icons'

import upload from '../api/upload'
import type { GetProp, UploadProps } from 'antd'
import getEnv from '../utils/env'

import './upload.scss'

interface IndexProps {
  maxLength: number
  defaultFileList: FileList[]
  change: (fileList: FileList[]) => void
  beforeUpload?: (file: File) => boolean
}

type UploadRequestOption = Parameters<GetProp<UploadProps, 'customRequest'>>[0]

export default function Index(props: IndexProps) {
  const { maxLength, defaultFileList, change, beforeUpload } = props

  const [fileList, setFileList] = useState<FileList[]>(defaultFileList)

  function customRequest(params: UploadRequestOption) {
    const { file } = params
    const formData = new FormData()
    formData.append('file', file)

    upload(formData).then(({ data }) => {
      fileList.push({ url: data! } as FileList)
      setFileList([...fileList])
      change(fileList)
    })
  }

  function deleteFile(index: number) {
    fileList.splice(index, 1)
    setFileList([...fileList])
    change(fileList)
  }

  return (
    <div className="upload">
      {fileList.map(({ url }, index) => {
        return (
          <div key={url} className="upload-preview">
            <img src={getEnv('img_url') + url} alt="" onClick={() => deleteFile(index)} />
          </div>
        )
      })}
      {fileList.length >= maxLength ? (
        ''
      ) : (
        <div className="upload-container">
          <Upload showUploadList={false} listType="picture-card" customRequest={customRequest} beforeUpload={beforeUpload}>
            <PlusOutlined></PlusOutlined>
          </Upload>
        </div>
      )}
    </div>
  )
}
